﻿using System;
using System.Linq.Expressions;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections.Generic;
using System.Xml.Linq;
using WCFCollection;

namespace RESTClientLibrary
{

	public class ClientCollection 
	{

		/// <summary>
		/// Collection name.
		/// </summary>
		private string _CollectionName;

		/// <summary>
		/// Initializes a new instance of the <see cref="ClientCollection"/> class.
		/// </summary>
		/// <param name="collectionName">Name of the collection.</param>
		/// <param name="endpoint">The endpoint.</param>
		public ClientCollection(string collectionName, string endpoint) 
		{
			_CollectionName = collectionName;
			Open(endpoint);

		}

		/// <summary>
		/// Gets the channel.
		/// </summary>
		/// <value>The channel.</value>
		public ICollectionService Channel
		{
			get;
			private set;
		}

		/// <summary>
		/// Opens the specified end point address.
		/// </summary>
		/// <param name="EndPointAddress">The end point address.</param>
		/// <returns>True if success; otherwise false.</returns>
		public bool Open(string EndPointAddress)
		{
			if (string.IsNullOrEmpty(EndPointAddress))
				EndPointAddress = "http://localhost:59474/Service.svc";
			WebHttpBinding binding;
			try
			{
				binding = new WebHttpBinding("HttpBindingSettings");
			}
			catch (KeyNotFoundException)
			{
				binding = new WebHttpBinding();
			}
			WebChannelFactory<ICollectionService> factory = new WebChannelFactory<ICollectionService>(binding, new Uri(EndPointAddress));
			Channel = factory.CreateChannel();
			return true;
		}


		/// <summary>
		/// Gets the linq result.
		/// </summary>
		/// <param name="linqQuery">The linq query.</param>
		/// <returns>Result of linq query as xml.</returns>
		public XElement GetLinqResult(string linqQuery)
		{
			return this.Channel.GetResultLinqInXml(_CollectionName, linqQuery);
		}

	}
}
